############################################################################            
#                             ADMINISTRATOR                                #
############################################################################

import cgi
import logging
from google.appengine.api import users
from google.appengine.ext import webapp
from db_model import Rooms, Members, Messages, FeedIndex



class MainPage(webapp.RequestHandler):
  
  def _handleRequest(self):
    self.response.out.write('<html><body>')
    self.response.out.write('Click on ')
    self.response.out.write('<a href="/Admin">administration</a>')
    self.response.out.write(' to get inside the admin page <br>')
    
  def get(self):
    self._handleRequest()


    
class AdminPage(webapp.RequestHandler):
  
  def _createForm(self, message, action, method, fields):
    html = []
    html.append('<b>%s</b>' % message)
    html.append('<form action="%s" method="%s">' % (action,method))
    html.append('User Id:<input type="text" name="UserId" /><br>')
    html.append('User Name (Nickname):<input type="text" name="UserName" value="%s"/><br>' % users.GetCurrentUser().email())
       
    for field in fields :
      html.append(field)
      html.append('<br>')
    html.append('<input type="submit" value="submit"/>')
    html.append('</form>')
    return ''.join(html)
       
  def _handleRequest(self):
    self.response.out.write("<html><body>")    
    self.response.out.write("Hello %s! <br><br>" % users.GetCurrentUser().email())
    self.response.out.write("<a href='%s'>logout</a><br><br>" % users.create_logout_url(self.request.uri))
    self.response.out.write("Goto app engine <a href='/_ah/admin'>admin</a><br><br>")
    
    self.response.out.write(self._createForm("Send Message",
                                             "/SendMessage",
                                             "Post",
                                             ['Message:<textarea name="Message" rows="1" cols="70"></textarea>',
                                             'Room Id:<input type="text" name="RoomId" />']))
    
    self.response.out.write(self._createForm("Send YouTube",
                                             "/SendYouTube",
                                             "Post",
                                             ['Headline:<input type="text" name="Headline" />',
                                              'Link:<input type="text" name="Link" />',
                                             'Room Id:<input type="text" name="RoomId" />']))
    
    self.response.out.write(self._createForm("Remove Message",
                                             "/RemoveMessage",
                                             "Post",
                                             ['Message Id:<input type="text" name="MessageId" />']))
    
    self.response.out.write(self._createForm("Create Room:",
                                             "/CreateRoom",
                                             "POST",
                                             ['Room name:<input type="text" name="RoomName" />']))
    
    self.response.out.write(self._createForm("Remove Room:",
                                             "/RemoveRoom",
                                             "POST",
                                             ['Room Id:<input type="text" name="RoomId" />']))
    
    self.response.out.write(self._createForm("Add Member",
                                             "/AddMember",
                                             "POST",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Member Id:<input type="text" name="MemberId" />',
                                              'Member Name:<input type="text" name="MemberName" />',
                                              'Member Email:<input type="text" name="MemberEmail" />']))
    
    self.response.out.write(self._createForm("Remove Member",
                                             "/RemoveMember",
                                             "POST",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Member Id:<input type="text" name="MemberId" />']))
    
    self.response.out.write(self._createForm("Change Nickname",
                                             "/ChangeNick",
                                             "POST",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'New Nickname:<input type="text" name="NewNick" />']))
    
    self.response.out.write(self._createForm("Get Room Messages",
                                             "/GetRoomMessages",
                                             "GET",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Max # of Messages:<input type="text" name="Messages" />',
                                              'Starting from message number :<input type="text" name="Offset" />']))
    
    self.response.out.write(self._createForm("Get Room Members",
                                             "/GetRoomMembers",
                                             "GET",
                                             ['Room Id:<input type="text" name="RoomId" />']))
                                                  
    self.response.out.write(self._createForm("Get User Rooms",
                                             "/GetUserRooms",
                                             "GET",
                                             []))
    
    self.response.out.write(self._createForm("Get Room Statistics",
                                             "/GetRoomStatistics",
                                             "GET",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Year:<input type="text" name="Year" />',
                                              'Month:<input type="text" name="Month" />',
                                              'Day:<input type="text" name="Day" />']))
    
    self.response.out.write(self._createForm("Get Word Count",
                                             "/GetWordCount",
                                             "GET",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Wanted Text:<input type="text" name="MyText" />',
                                              'Max # of Messages:<input type="text" name="Messages" />']))
    
    self.response.out.write(self._createForm("Create Poll",
                                             "/CreatePoll",
                                             "POST",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Question:<input type="text" name="Question" />',
                                              'Answer JSON: (example: ["yes","no"]) <input type="text" name="Answers" />']))
    
    self.response.out.write(self._createForm("Answer Poll",
                                             "/AnswerPoll",
                                             "POST",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Poll Id:<input type="text" name="PollId" />',
                                              'Answer Number:<input type="text" name="AnswerNumber" />']))
    
    self.response.out.write(self._createForm("Get Room Polls",
                                             "/GetRoomPolls",
                                             "GET",
                                             ['Room Id:<input type="text" name="RoomId" />',
                                              'Polls:<input type="text" name="Polls" />']))
    
    self.response.out.write(self._createForm("Get User feed",
                                             "/GetUserFeed",
                                             "GET",
                                             ['Max # of Messages:<input type="text" name="Messages" />',
                                              'Starting from message number :<input type="text" name="Offset" />']))
    
    self.response.out.write(self._createForm("Number Of New Messages",
                                             "/NumOfNewMessages",
                                             "GET",
                                             ['Room Id:<input type="text" name="RoomId" />',                          
                                              'Time :<input type="text" name="Time" />']))
    
    self.response.out.write("<script>")
    self.response.out.write("function areYouSure() { return confirm('To delete the entire DB?'); }")
    self.response.out.write("</script>")
    self.response.out.write("<form method='POST' action='/TrancateDB'>")
    self.response.out.write("<input type='submit' value='cleaer ALL db' onclick='return areYouSure()' />")
    self.response.out.write("</form>")
    
    self.response.out.write("</body></html>")
    
    
    
  def get(self):
    if not users.GetCurrentUser():
      self.redirect(users.create_login_url(self.request.uri))
      return
  
    if not users.IsCurrentUserAdmin():
      self.response.out.write("Hello %s!<br>" % users.GetCurrentUser().email())
      self.response.out.write('You must be an admin to view this page.<br>')
      self.response.out.write("<a href='%s'>logout</a>" % users.create_logout_url(self.request.uri))
      return
  
    self._handleRequest()
    
    

class TrancateDB(webapp.RequestHandler):
  
  def post(self):
    if not users.GetCurrentUser():
      self.redirect(users.create_login_url(self.request.uri))
      return
  
    if not users.IsCurrentUserAdmin():
      self.response.out.write("please log in as an admin")
      
    messages = Messages.Query()
    for message in messages:
      message.delete()
    
    #remove from Members
    members = Members.Query()
    for member in members :
      member.delete()
      
    #remove from Messages
    rooms = Rooms.Query()
    for room in rooms :
      room.delete()
    
    #remove indexes
    feedIndex = FeedIndex.Query()
    for feedEntity in feedIndex :
      feedEntity.delete()
      
    self.response.out.write("deleted")
    return   